<template>
	<jk-dialog
		v-model="showDialog"
		:title="dataItem.date ? `${dataItem.date}-排班` : '排班'"
		width="800px"
		:append-to-body="true"
		:show-cancel-btn="false"
		:show-confirm-btn="false"
		@on-visible-change="onVisibleChange"
		@on-cancel="onVisibleChange(false)"
	>
		<el-form label-width="80px" class="schedule-form-container">
			<el-row>
				<el-col :span="12">
					<el-form-item label="日期" class="margin-bottom-10">
						<span class="read-only-2">{{ ruleForm.belongDate }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="区域" class="margin-bottom-10">
						<span class="read-only-2">{{ ruleForm.workshopName }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="班制" class="margin-bottom-10">
						<div class="flex-between-center">
							<el-radio-group v-model="ruleForm.shiftTypeId" size="medium" @change="onSelectShiftType">
								<el-radio-button v-for="(item, index) in shiftTypeList" :key="index" border :label="item.id">{{ item.name }}</el-radio-button>
							</el-radio-group>
							<el-button circle icon="el-icon-refresh" @click="getShiftListRequest"></el-button>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="班次/班组" class="margin-bottom-10">
						<el-alert
							show-icon
							style="height: 34px;"
							title="注：'复制'是指排入某个日期下的班组及人员;当然,你也可以通过'选择'的方式排入班组及最新的人员."
							type="warning"
							class="margin-bottom-4"
							:closable="false"
						></el-alert>
						<div v-loading="tableLoading" class="schedule-shift-container">
							<div
								v-for="(item, index) in ruleForm.scheduleShiftList"
								:key="index"
								class="schedule-shift-item"
							>
								<div class="schedule-shift-item-header">
									<span>{{ item.shiftName }}</span>
									<span class="schedule-shift-item-header-hour">({{ `${item.beginTime} ~ ${item.endTime}` }})</span>
								</div>
								<div class="schedule-shift-group-box">
									<el-tag
										v-for="(groupItem, groupIndex) in item.scheduleGroupList"
										:key="groupIndex"
										closable
										size="large"
										class="schedule-shift-group-item"
										@close="onRemoveGroup(index, groupIndex)"
									>{{ groupItem.groupName }}</el-tag>
									<div v-if="!item.scheduleGroupList || !item.scheduleGroupList.length" class="no-data">暂无班组</div>
								</div>
								<div class="flex-start-center">
									<!--<div class="item-gap width-100-percent"><el-button class="width-100-percent" plain icon="el-icon-document-copy" @click="onCopyBtn(index)">复制</el-button></div>-->
									<el-popover v-model="item.selectGroupPopoverState" width="500" title="选择班组" trigger="click" class="width-100-percent">
										<!--<el-checkbox-group v-model="checkedArr" size="small" class="flex-start-center-wrap">
											<div
												v-for="(optionItem, optionIndex) in groupList"
												:key="optionIndex"
												style="width: calc(100% / 4);padding: 4px 2px;box-sizing: border-box;"
											>
												<el-checkbox
													:label="optionItem.id"
													border
													:disabled="disabledArr.some(x => x === optionItem.id)"
													style="width: 100%;margin: 0 2px;"
													class="item-gap"
												>{{ optionItem.name }}</el-checkbox>
											</div>
										</el-checkbox-group>-->
										<el-radio-group v-model="checkedArr" size="small" class="flex-start-center-wrap">
											<div
												v-for="(optionItem, optionIndex) in groupList"
												:key="optionIndex"
												style="width: calc(100% / 4);padding: 4px 2px;box-sizing: border-box;"
											>
												<el-radio
													:label="optionItem.id"
													border
													:disabled="disabledArr.some(x => x === optionItem.id)"
													style="width: 100%;margin: 0 2px;"
													class="item-gap"
												>{{ optionItem.name }}</el-radio>
											</div>
										</el-radio-group>
										<div class="margin-top-10 flex-start-center">
											<el-button type="danger" class="width-100-percent" @click="item.selectGroupPopoverState = false">取消</el-button>
											<el-button type="primary" class="width-100-percent" :loading="selectGroupConfirmButtonLoading" @click="onConfirmSelectGroupPopover(index)">确定</el-button>
										</div>
										<div slot="reference" class="flex-start-center width-100-percent">
											<div class="width-100-percent"><el-button plain class="width-100-percent" icon="el-icon-plus" @click="onAddBtn(item.scheduleGroupList)">选择</el-button></div>
										</div>
									</el-popover>
								</div>
							</div>
							<div v-if="!ruleForm.scheduleShiftList || !ruleForm.scheduleShiftList.length" class="no-data">暂无班次</div>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="margin-top-10">
					<div class="flex-center">
						<el-button size="medium" class="item-gap" icon="el-icon-close" @click="onVisibleChange(false)">取消</el-button>

						<el-button v-if="!ruleForm.id" slot="reference" size="medium" icon="el-icon-check" type="primary" :loading="confirmButtonLoading" @click="onConfirmBtn(false)">确定</el-button>
						<el-popconfirm
							v-else
							confirm-button-text="只改当前日期"
							cancel-button-text="重排后续日期"
							icon="el-icon-info"
							icon-color="red"
							title="请酌情选择操作事项!"
							@cancel="onConfirmBtn(true)"
							@confirm="onConfirmBtn(false)"
						>
							<el-button slot="reference" size="medium" icon="el-icon-check" type="primary">确定</el-button>
						</el-popconfirm>
					</div>
				</el-col>
			</el-row>
			<copy-group-dialog
				:params="copyGroupDialogParams"
				:dialog-state="copyGroupDialogState"
				@on-visible-change="onVisibleChangeOfCopyGroupDialog"
				@on-confirm="onConfirmOfCopyGroupDialog"
			></copy-group-dialog>
		</el-form>
	</jk-dialog>
</template>
<script>
    import calDialogHeight from '../../../mixins/cal-dialog-height';
    import {
        workforcemanagementScheduleCreate, workforcemanagementScheduleGet,
        workforcemanagementScheduleUpdate
    } from '../../../api/schedule/scheduling';
    import { workforcemanagementShiftPage } from '../../../api/schedule/shift';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import { personnelGroupPage } from '../../../api/personnel/group';
    import copyGroupDialog from './compomens/copy-group-dialog';
    import { tipsBar } from '../../../utils/jk/jk-tool';
    export default {
        name: 'SaveScheduleDialog',
        components: {
            copyGroupDialog
        },
        mixins: [calDialogHeight],
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            dataItem: {
                type: Object,
                default() {
                    return {
                        workshopId: null,
                        workshopName: '',
                        date: [],
                        shiftList: []
                    };
                }
            }
        },
        data() {
            return {
                disabledArr: [],
                copyGroupDialogParams: {},
                copyGroupDialogState: false,
                checkedArr: null,
                ruleForm: {
                    id: null,
                    belongDate: '',
                    workshopId: null,
                    workshopCode: '',
                    workshopName: '',
                    shiftTypeId: null,
                    shiftTypeCode: '',
                    shiftTypeName: '',
                    scheduleShiftList: []
                },
                showDialog: false,
                radioValue: 1,
                tableData: [],
                shiftTypeList: [],
                groupList: [],
                tableLoading: false,
                confirmButtonLoading: false,
                editShiftIndex: null,
                selectGroupConfirmButtonLoading: false
            };
        },
        methods: {
            onConfirmOfCopyGroupDialog(e) {
                this.ruleForm.scheduleShiftList[this.editShiftIndex].scheduleGroupList.push({
                    groupId: e.groupId,
                    groupCode: e.groupCode,
                    groupName: e.groupName,
                    copyScheduleGroupId: e.id
                });
                this.copyGroupDialogState = false;
            },
            onCopyBtn(index) {
                this.editShiftIndex = index;
                this.copyGroupDialogParams = {
                    selectedIds: this.ruleForm.scheduleShiftList[this.editShiftIndex].scheduleGroupList.map(x => x.groupId),
                    workshopId: this.ruleForm.workshopId,
                    belongDate: this.ruleForm.belongDate
                };
                this.copyGroupDialogState = true;
            },
            onVisibleChangeOfCopyGroupDialog(e) {
                this.copyGroupDialogState = e;
            },
            onAddBtn(scheduleGroupList) {
                this.checkedArr = null;
                this.disabledArr = scheduleGroupList.map(p => p.groupId);
            },
            onConfirmSelectGroupPopover(idx) {
                this.selectGroupConfirmButtonLoading = true;
                let arr = null;
                this.groupList.map(x => {
                    /* this.checkedArr.forEach(k => {
                        if (x.id === k) {
                            arr.push({
                                groupId: x.id,
                                groupCode: x.code,
                                groupName: x.name
                            });
                        }
                    });*/
                    if (x.id === this.checkedArr) {
                        arr = {
                            groupId: x.id,
                            groupCode: x.code,
                            groupName: x.name
                        };
                    }
                });
                if (arr) {
                    this.$set(this.ruleForm.scheduleShiftList[idx], 'scheduleGroupList', [arr]);
                }
                /* arr.forEach(x => {
                    this.ruleForm.scheduleShiftList[idx].scheduleGroupList.push(x);
                });*/
                this.$set(this.ruleForm.scheduleShiftList[idx], 'selectGroupPopoverState', false);
                // 延迟处理，避免连续快速点击导致的重复添加的问题
                setTimeout(() => {
                    this.selectGroupConfirmButtonLoading = false;
                }, 500);
            },
            onRemoveGroup(shiftIdx, groupIdx) {
                this.ruleForm.scheduleShiftList[shiftIdx].scheduleGroupList.splice(groupIdx, 1);
            },
            onSelectShiftType() {
                this.getShiftListRequest();
            },
            saveRequest(ifCoverage) {
                this.confirmButtonLoading = true;
                const scheduleShiftList = JSON.parse(JSON.stringify(this.ruleForm.scheduleShiftList));
                const shiftItem = this.shiftTypeList.find(item => item.id === this.ruleForm.shiftTypeId) || {};
                const params = {
                    id: this.ruleForm.id,
                    belongDate: this.ruleForm.belongDate,
                    workshopId: this.ruleForm.workshopId,
                    workshopCode: this.ruleForm.workshopCode,
                    workshopName: this.ruleForm.workshopName,
                    shiftTypeId: this.ruleForm.shiftTypeId,
                    shiftTypeName: shiftItem.name,
                    shiftTypeCode: shiftItem.code,
                    scheduleShiftList: scheduleShiftList,
                    ifCoverage: ifCoverage
                };
                const api = !this.ruleForm.id ? workforcemanagementScheduleCreate : workforcemanagementScheduleUpdate;
                if (!this.ruleForm.id) delete params.id;
                return api(params).then(res => {
                    this.confirmButtonLoading = false;
                    if (res.data.status === 200) {
                        this.$emit('on-confirm');
                        this.$tipsBar(this, 'save');
                    }
                });
            },
            onConfirmBtn(type) {
                if (this.ruleForm.scheduleShiftList && this.ruleForm.scheduleShiftList.length) {
                    this.saveRequest(type);
                } else {
                    this.$tipsBar(this, 'custom', 'warning', '班次不能为空!');
                }
            },
            // 班次
            getShiftListRequest() {
                this.tableLoading = true;
                return workforcemanagementShiftPage({
                    'typeId': this.ruleForm.shiftTypeId,
                    'workshopId': this.ruleForm.workshopId,
                    'auditState': 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm.scheduleShiftList = res.data.res.map(item => {
                            return {
                                beginTime: item.beginHour,
                                endTime: item.endHour,
                                scheduleGroupList: [],
                                workingHours: item.workingHours,
                                shiftId: item.id,
                                shiftName: item.name,
                                selectGroupPopoverState: false
                            };
                        });
                    }
                    this.tableLoading = false;
                });
            },
            // 班制(从班次档案获取，根据车间筛选并去重, 目的是只展示该车间相关的班制)
            getShiftTypeRequest() {
                return workforcemanagementShiftPage({
                    'workshopId': this.ruleForm.workshopId,
                    'auditState': 1
                }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || [];
                        const arr = [];
                        resData.forEach(item => {
                            if (!arr.some(x => x.id)) {
                                arr.push({
                                    id: item.typeId,
                                    code: item.typeCode,
                                    name: item.typeName
                                });
                            }
                        });
                        this.shiftTypeList = arr;
                        if (!this.ruleForm.shiftTypeId && this.shiftTypeList && this.shiftTypeList.length) {
                            this.$set(this.ruleForm, 'shiftTypeId', this.shiftTypeList[0].id);
                            this.getShiftListRequest();
                        }
                    }
                });
            },
            // 班组
            getGroupListRequest() {
                return personnelGroupPage({ auditState: 1, workshopId: this.ruleForm.workshopId }).then(res => {
                    if (res.data.status === 200) {
                        this.groupList = res.data.res;
                    }
                });
            },
            getDetailRequest() {
                return workforcemanagementScheduleGet({ id: this.ruleForm.id }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.scheduleShiftList = resData.scheduleShiftList || [];
                        resData.scheduleShiftList.forEach(x => {
                            x.scheduleGroupList = x.scheduleGroupList || [];
                        });
                        this.ruleForm = resData;
                    }
                });
            },
            async getDependentData() {
                const cpData = JSON.parse(JSON.stringify(this.dataItem));
                this.$set(this.ruleForm, 'id', cpData.scheduleId || null);
                if (!this.ruleForm.id) {
                    this.$set(this.ruleForm, 'workshopId', cpData.workshopId);
                    this.$set(this.ruleForm, 'workshopCode', cpData.workshopCode);
                    this.$set(this.ruleForm, 'workshopName', cpData.workshopName);
                    this.$set(this.ruleForm, 'belongDate', cpData.date);
                }
                this.tableLoading = true;
                if (this.ruleForm.id) await this.getDetailRequest();
                await this.getShiftTypeRequest();
                await this.getGroupListRequest();
                this.tableLoading = false;
            },
            onVisibleChange(e) {
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
                this.$emit('on-visible-change', e);
            }
        },
        watch: {
            dialogState(newVal) {
                if (newVal) {
                    this.getDependentData();
                }
                this.showDialog = newVal;
            }
        }
    };
</script>
<style scoped lang="scss">
.schedule-form-container {
    margin: 10px 0;
    padding: 16px;
    border: solid 1px #eee;
    border-radius: 2px;
    overflow: auto;
    .schedule-shift-container {
        width: 100%;
        min-height: 100px;
        border: solid 1px #eee;
        display: flex;
        align-items: center;
        .schedule-shift-item {
            width: 100%;
            border-right: solid 1px #eee;
            .schedule-shift-item-header {
                height: 42px;
                border-bottom: solid 1px #eee;
                background: #f8f8f9;
                line-height: 14px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                font-size: 14px;
                .schedule-shift-item-header-hour {
                    font-size: 12px;
                    color: #808695;
                    margin-top: 2px;
                }
            }
            .schedule-shift-group-box {
                width: 100%;
                height: 200px;
                padding: 8px 12px;
                box-sizing: border-box;
                .schedule-shift-group-item {
                    width: 100%;
                    margin: 6px 0;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                }
            }
        }
        .no-data {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 13px;
        }
    }
    .schedule-shift-container .schedule-shift-item:last-child {
        border-right: none;
    }
}
</style>
